package com.liuceng.zen.web.controller;

import com.alibaba.fastjson.JSONArray;
import com.liuceng.zen.Page;
import com.liuceng.zen.pojo.domain.BaseDomain;
import com.liuceng.zen.pojo.domain.FrontAdGroup;
import com.liuceng.zen.pojo.domain.Member;
import com.liuceng.zen.pojo.form.DashboardForm;
import com.liuceng.zen.service.DashboardService;
import com.liuceng.zen.service.FrontAdGroupService;
import com.liuceng.zen.service.GdtAdGroupService;
import com.liuceng.zen.service.MemberService;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Controller
@RequestMapping(value = "/dashboard")
public class DashboardController extends BaseController {
  private final static Logger LOG = LoggerFactory.getLogger(DashboardController.class);


  @Autowired
  MemberService memberService;
  @Autowired
  DashboardService dashboardService;
  @Autowired
  GdtAdGroupService gdtAdGroupService;
  @Autowired
  FrontAdGroupService frontAdGroupService;

  // 首页---现金账户、当前广告数
  @RequestMapping(value = "")
  public String dashboard(@ModelAttribute("form") DashboardForm form, HttpServletRequest req) {
    // 获取登录客户的信息
    Member member = memberService.find(getCurrentUserId());
    form.setMemberId(getCurrentUserId());
    // 广告个数
    form.setMemberId(getCurrentUserId());
    Page<FrontAdGroup> page = frontAdGroupService.findPage(form);
    Integer adNum = page.getTotalCount();
    // 现金账户余额
    form.setBalance(member.getBalance());
    // 最后充值时间
    form.setBalanceAt(member.getUpdatedAt());
    form.setAdNum(adNum);
    form.setAdNumAt(null);
    Boolean backend = getUserContext().isFromBackend();
    String system = (String) req.getSession().getAttribute("system");
    if(backend&&system=="false"){
      return "redirect:/campaigns/list";
    }
    return "/dashboard";
  }

  // 首页---总体情况动态获取
  @RequestMapping(value = "data")
  public String dashboardData(@ModelAttribute("form") DashboardForm form, HttpServletRequest req) throws ParseException {
    // 今天、昨天、过去七天、过去三十天，自定义，ajax请求获取数据
    final String TODAY = "1";
    final String YESTERDAY = "2";
    final String LAST_7_DAYS = "3";
    final String LAST_30_DAYS = "4";
    final String USER_DEFINED="5";

    String timeType =
        req.getParameter("timeType") == null ? LAST_7_DAYS : req.getParameter("timeType").toString();
    // 今天时间
    Date endDate = DateUtils.addDays(new Date(), 0);
    Date startDate = null;
    String aaa=req.getParameter("startDate");
    String bbb=req.getParameter("endDate");
    // 根据时间格式判断是哪个选择
    switch (timeType) {
      case YESTERDAY:
        startDate = DateUtils.addDays(endDate, -1);
        endDate = DateUtils.addDays(endDate, -1);
        break;
      case LAST_7_DAYS:
        startDate = DateUtils.addDays(endDate, -6);
        break;
      case LAST_30_DAYS:
        startDate = DateUtils.addDays(endDate, -29);
        break;
      case USER_DEFINED:
        startDate=new SimpleDateFormat("yyyy-MM-dd").parse(req.getParameter("startDate"));
        endDate=new SimpleDateFormat("yyyy-MM-dd").parse(req.getParameter("endDate"));
        break;
      case TODAY:
      default:
        startDate = endDate;
    }
    //
    Map<String, Object> params = new HashMap<>();
    params.put("startDate", DateFormatUtils.format(startDate, "yyyy-MM-dd"));
    params.put("endDate", DateFormatUtils.format(endDate, "yyyy-MM-dd"));
    params.put("memberId", getCurrentUserId());
    params.put("auditType", BaseDomain.AUDIT_PASS);
    // 获得总花费，总曝光量，总点击量
    Map<String, Object> totalData = dashboardService.findTotalData(params);
    // 按天分隔，获取每天的总花费，总曝光量，总点击量
      List<Map<String, Object>> data=new ArrayList<>();
      if(startDate.equals(endDate)&& getUserContext().getMember().getOperationType()==2){
          data = dashboardService.findRptHourList(params);
      }else{
          data = dashboardService.findDataList(params,DateFormatUtils.format(startDate, "yyyy-MM-dd"),DateFormatUtils.format(endDate, "yyyy-MM-dd"));
      }

    //
    form.setTotalData(totalData);
    form.setData(data.stream().map(d -> {
      d.put("total_cost",d.get("total_cost")==null?new BigDecimal(0) :((BigDecimal)d.get("total_cost")).divide(new BigDecimal(1), 2, RoundingMode.HALF_DOWN));
      return JSONArray.toJSON(d);
    }).collect(Collectors.toList()));
    form.setTimeSelect(timeType);

    return "/_dashboard_data";
  }
}
